package com.smartsofa.adapter;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.smartsofa.R;
import com.smartsofa.entity.Topic;
import com.smartsofa.entity.User;
import com.smartsofa.photo.GifView;
import com.smartsofa.util.AsyncImageLoader;
import com.smartsofa.util.MyUtils;

public class TopicCommentListAdapter extends BaseAdapter {
	
	protected int topicId;
	ViewHolder holder;
	private List<Map<String,Object>> mData;
	private JSONObject topicobj;
	private LayoutInflater mInflater;
	private Context mContext;
	
	
	private String url;
	private Boolean flag;
	private Topic topic;
	
	private JSONObject json;
		
	//定义网络连接超时判定变量
	private boolean network_timeout=false;
	
	//异步加载图片
	private AsyncImageLoader imageLoader;

    public final class ViewHolder{           
        public ImageView img_user2;
        public TextView tv_username;
        public TextView tv_commenttime_value;
        public TextView tv_comment;
        public TextView tv_floornum;
      }
    public TopicCommentListAdapter(Context context,JSONObject topicobj){
    	this.mInflater = LayoutInflater.from(context); 
		this.mContext = context;
		imageLoader = new AsyncImageLoader(context);
		this.topicobj = topicobj;
    }
	
    public TopicCommentListAdapter(Context context, List<Map<String,Object>> data,JSONObject topicobj){      
    	this.mInflater = LayoutInflater.from(context); 
		this.mContext = context;
		this.mData = data;
		this.topicobj = topicobj;
		imageLoader = new AsyncImageLoader(context);
    } 

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		if(mData==null){
			return 1;
		}else{
		 return mData.size()+1;
		}
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub			
		return mData.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return arg0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub 
		if(position !=0){
		
			holder=new ViewHolder();     
            convertView = mInflater.inflate(R.layout.listview_topic_comments, null);        
            
            holder.img_user2=(ImageView)convertView.findViewById(R.id.topic_comment_userimg);
            holder.tv_username=(TextView)convertView.findViewById(R.id.tv_username);
            holder.tv_commenttime_value=(TextView)convertView.findViewById(R.id.tv_commenttime_value);
            holder.tv_comment=(TextView)convertView.findViewById(R.id.tv_comment);
            holder.tv_floornum=(TextView)convertView.findViewById(R.id.tv_floornum);
            convertView.setTag(holder); 
            holder.img_user2.setBackgroundResource(R.drawable.user_img2);
            holder.tv_username.setText(mData.get(position-1).get("userName").toString());
            holder.tv_comment.setText(mData.get(position-1).get("comment").toString());
            holder.tv_commenttime_value.setText(mData.get(position-1).get("commentTime").toString());
            holder.tv_floornum.setText(mData.get(position-1).get("floorNum").toString());
        
     // 预设一个图片
  		holder.img_user2.setBackgroundResource(R.drawable.user_img2);
  		if (mData.get(position-1).containsKey("userImg")&&!("").equals(mData.get(position-1).get("userImg"))) {
  			final String imgUrl = (String) mData.get(position-1).get("userImg");
  			// 给 ImageView 设置一个 tag
  			holder.img_user2.setTag(imgUrl);
  			if (!TextUtils.isEmpty(imgUrl)) {
  				Bitmap bitmap = imageLoader.loadImage(holder.img_user2, imgUrl);
  				if (bitmap != null) {
  					holder.img_user2.setImageBitmap(bitmap);
  				}
  			}
  		}
		}else{
			convertView = mInflater.inflate(R.layout.detailtopictop, null);
			GifView gifView1 = (GifView)convertView.findViewById(R.id.gif1);
			ImageView img_user2=(ImageView)convertView.findViewById(R.id.detail_topic_userimg);
			TextView tv_username=(TextView)convertView.findViewById(R.id.tv_username);
			TextView tv_topictime_value=(TextView)convertView.findViewById(R.id.tv_topictime_value);
			TextView tv_topic_content=(TextView)convertView.findViewById(R.id.tv_topic_content);
			TextView img_bt_praise=(Button)convertView.findViewById(R.id.img_bt_praise);
			TextView tv_topic_praise=(TextView)convertView.findViewById(R.id.tv_topic_praise);
			TextView img_bt_comment=(Button)convertView.findViewById(R.id.img_bt_comment);
			TextView tv_topic_comment=(TextView)convertView.findViewById(R.id.tv_topic_comment);
			ImageView fImageView = (ImageView)convertView.findViewById(R.id.fimg_view);
			img_user2.setBackgroundResource(R.drawable.user_img2);
			//点赞监听事件
			img_bt_praise.setOnClickListener(new OnClickListener(){
	        	
	            public void onClick(View arg0) {  
	                // TODO Auto-generated method stub                            	
	                Thread praise_thread=new Thread(new praiseNetThread(topic.getTopicId()));
	                praise_thread.start();
	            }
	        });
			
			try {
				String imgUrl2 = topicobj.getString("userImg");
				AsyncImageLoader imageLoader=new AsyncImageLoader(mContext);
				Bitmap bitmap = imageLoader.loadImage(img_user2, imgUrl2);
					if (bitmap != null) {
						img_user2.setImageBitmap(bitmap);
					}
					tv_username.setText(topicobj.getString("userName"));
					tv_topictime_value.setText(topicobj.getString("publicTime"));
					tv_topic_content.setText(topicobj.getString("topicContent"));
					tv_topic_praise.setText(topicobj.getString("praiseNum"));
					tv_topic_comment.setText(topicobj.getString("commentNum"));		
					if(!topicobj.isNull("imgUrl")){
						//显示预设的图片
						gifView1.setMovieResource(R.raw.loading);
						gifView1.setVisibility(View.VISIBLE);
						String fimgUrl=topicobj.getString("imgUrl");
						fimgUrl.replace("\\", "");
						Log.i("发帖url", fimgUrl);
						AsyncImageLoader fimageLoader=new AsyncImageLoader(mContext);
						Bitmap fbitmap = fimageLoader.loadImage(fImageView, fimgUrl);
						if(fbitmap != null){
							gifView1.setVisibility(View.GONE);
							fImageView.setImageBitmap(fbitmap);
							fImageView.setAdjustViewBounds(true);
							fImageView.setMaxWidth(mContext.getResources().getDisplayMetrics().widthPixels);
							fImageView.setMaxHeight(fbitmap.getHeight());
							fImageView.setVisibility(View.VISIBLE);							
						}
						else{
							gifView1.setVisibility(View.GONE);
							fImageView.setBackgroundResource(R.drawable.loaingfall);
							fImageView.setVisibility(View.VISIBLE);
						}				
					
			}
			}catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
				
			
		}		  
        return convertView;        
        }
	/**
	 * 点赞线程
	 * @author YuHuan
	 *
	 */
	class praiseNetThread implements Runnable{
		int topicId;
		public praiseNetThread(int topicId){
			this.topicId=topicId;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {			
				url=MyUtils.getUrl()+"topic_praiseTopic?topicid="+topicId;					
				HttpGet request = new HttpGet(url);		
				//以下三行为连接服务器超时判断，如果超时将不执行以下所有代码
			   BasicHttpParams httpParams = new BasicHttpParams();
			   HttpConnectionParams.setConnectionTimeout(httpParams,MyUtils.REQUEST_TIMEOUT);
		       HttpClient httpClient = new DefaultHttpClient(httpParams);
		       HttpResponse httpResponse = httpClient.execute(request);							       
		       	
		      if (httpResponse.getStatusLine().getStatusCode() == 200) {
		    	network_timeout=true;
		        String jsonString = EntityUtils.toString(httpResponse.getEntity());
		        json = new JSONObject(jsonString);
		        flag=(Boolean) json.get("success");			        				      		       
		      }
		      }catch (Exception e) {
		        	 e.printStackTrace();
		      }
			Message msg = praise_handler.obtainMessage();
			if(network_timeout){
				if (flag) {				
					msg.what = 1;									
				}else{
					msg.what = 2;			
				}
			}			
			else{
				msg.what = 3;						
			}
			praise_handler.sendMessage(msg);			
		}	
	}
	Handler praise_handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {		
			case 1:
				Toast.makeText(mContext, "点赞成功！", Toast.LENGTH_SHORT).show();	
				notifyDataSetChanged();
				break;
			case 2:
				Toast.makeText(mContext, "操作失败，请稍后再试！", Toast.LENGTH_SHORT).show();
				break;
			case 3:
				Toast.makeText(mContext, "网络连接超时！", Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};
	public void setTopic(Topic topic){
		this.topic = topic;
	}

	
}
